﻿using System.Collections.Generic;
using System.Linq;
using Calendar.Logic.Core;
using Calendar.Logic.ObjectModel.Authorization;

namespace Calendar.Logic.ObjectManager.Authorization
{
    internal static class UserRoleManagerExtended
    {
        public static IQueryable<User> SelectUsersByRole(this IQueryable<UserRole> table, string roleName)
        {
            return table.Where(ur => ur.ScnEntity.Rolename == roleName && ur.ScnEntity.ApplicationName == GlobalContext.Instance.ApplicationName).Select(ur => ur.FrsEntity).Distinct();
        }

        public static IQueryable<Role> SelectRolesByUser(this IQueryable<UserRole> table, string userName)
        {
            return table.Where(ur => ur.FrsEntity.Username == userName && ur.FrsEntity.ApplicationName == GlobalContext.Instance.ApplicationName).Select(ur => ur.ScnEntity).Distinct();
        }

        public static IQueryable<User> SelectUsersByRole(this IQueryable<UserRole> table, Role role)
        {
            return table.Where(ur => ur.ScnEntity.ID == role.ID && ur.ScnEntity.ApplicationName == GlobalContext.Instance.ApplicationName).Select(ur => ur.FrsEntity).Distinct();
        }

        public static IQueryable<Role> SelectRolesByUser(this IQueryable<UserRole> table, User user)
        {
            return table.Where(ur => ur.FrsEntity.ID == user.ID && ur.FrsEntity.ApplicationName == GlobalContext.Instance.ApplicationName).Select(ur => ur.ScnEntity).Distinct();
        }

        public static bool ExistsUserInRole(this IQueryable<UserRole> table, string username, string rolename)
        {
            return table.Any(ur => ur.FrsEntity.Username == username && ur.FrsEntity.ApplicationName == GlobalContext.Instance.ApplicationName 
                                && ur.ScnEntity.Rolename == rolename && ur.FrsEntity.ApplicationName == GlobalContext.Instance.ApplicationName);
        }
    }

    public class UserRoleManager : BaseManager<UserRoleManager, UserRole, User, Role>
    {

        public List<User> SelectAllUsers()
        {
            return Table.SelectUsersByRole(AppRole.Пользователь.ToString()).ToList();
        }

        public List<User> SelectAllAdministrators()
        {
            return Table.SelectUsersByRole(AppRole.Администратор.ToString()).ToList();
        }

        public void AddUserRole(int userId)
        {
            var userRole = CreateInstance();
            userRole.FRS_ID = userId;
            userRole.SCN_ID = 2;
            Insert(userRole);
        }
    }
}
